package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.domain.Catalog;
import cn.wolfcode.shop.service.ICatalogService;
import cn.wolfcode.shop.vo.JsonResultVO;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class CatalogController {
    @Reference
    private ICatalogService catalogService;

    @RequestMapping("main")
    public String main(){
        return "main";
    }
    @RequestMapping("index")
    public String index(){
        return "index";
    }

    /**
     * 商品分类
     * @param model
     * @return
     */
    @RequestMapping("catalog")
    public String catalog(Model model){
        List<Catalog> catalogs = catalogService.selectAll();
        model.addAttribute("allCatalogJson",JSON.toJSONString(catalogs));
        return "catalog/catalog";
    }

    /**
     * 子商品列表(根据商品的pid查询)
     * @param model
     * @param catalogId 父id
     * @return
     */
    @RequestMapping("catalog/getChildCatalog")
    public String getChildCatalog(Model model,Long catalogId){
        List<Catalog> childCatalogs =catalogService.selectByCatalogPid(catalogId);
        model.addAttribute("catalogList",childCatalogs);
        return "catalog/child_catalog";

    }

    /**
     * 商品添加分类
     * @param catalog
     * @return
     */
    @RequestMapping("catalog/save")
    @ResponseBody
    public JsonResultVO saveOrUpdate(Catalog catalog){
        catalogService.saveOrUpdate(catalog);
        return JsonResultVO.success();
    }

    /**
     * 删除当前分类
     * @param catalogId
     * @return
     */
    @RequestMapping("catalog/delete")
    @ResponseBody
    public JsonResultVO delete(Long catalogId){
        //查询该分类是否是目录,如果是不能删除
        Catalog catalog = catalogService.selectByCatalogId(catalogId);
        List<Catalog> childCatalog = catalogService.selectChildByCatalog(catalogId);

        if(catalog.isParent() && childCatalog.size()!=0 ){
            JsonResultVO.error("目录不能删除");
        }else {
            catalogService.delete(catalogId);
        }
        return JsonResultVO.success();
    }

    /**
     * 给需要做拖拽排序
     * @param ids
     * @return
     */
    @RequestMapping("catalog/updateSort")
    @ResponseBody
    public JsonResultVO updateSort(@RequestBody Long[] ids){
        catalogService.updateSort(ids);

        return JsonResultVO.success();
    }

}
